-- UIMonsterCaptain
-- Created by zouyb Dec/30/2015
-- 海怪船长主界面

require "game/ui/form/dungeon/special/UIMonsterCaptainEquip"

UIMonsterCaptain = class("UIMonsterCaptain", function()
    return cc.Layer:create();
end);

function UIMonsterCaptain.create(summon)
    return UIMonsterCaptain.new(summon);
end

-- 获取显示列表
local equipList = {7262, 7261, 7263, 0};

-- 模型缩放比例
local MODEL_SCALE = 1.2;

-- 光效缩放比例
local EFFECT_SCALE = 1.5;

function UIMonsterCaptain:ctor(summon)
    -- 初始化
    self:setName("UIMonsterCaptain");
    local node = cc.CSLoader:createNode("layout/dungeon/special/MonsterCaptain.csb");
    self:addChild(node);
    self.node = node;

	self.summon = summon;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化窗口
    self:initForm();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 部分控件位置修正
function UIMonsterCaptain:fixPos(desc1, desc2, nameLabel)
    -- desc1的Y轴位置
    local positionY = desc1:getPositionY();

    -- desc1文本控件的高度
    local labelHeight = getRealContentSize(desc1).height;

    -- 设置desc2的位置
    desc2:setPositionY(positionY - labelHeight - 6);

    local labelHeight2 = getRealContentSize(desc2).height;

    local nameHeight = getRealContentSize(nameLabel).height;

    local tipBg = findChildByName(self.node, "CT/tip_bg");
    local totalHeight = nameHeight + labelHeight + labelHeight2 + 50;

    if tipBg.initSize == nil then
        tipBg.initSize = tipBg:getContentSize();
    end

    -- 适配高度（不能超出背景，固定加20）
    if totalHeight >  tipBg.initSize.height then
        tipBg:setContentSize(tipBg.initSize.width, tipBg.initSize.height + 20);
    end
end

-- 适配
function UIMonsterCaptain:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIMonsterCaptain:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UIMonsterCaptain", event.BLACKSMITH_INPUT_EQUIP, function(args)
        self:whenInputEquip(args);
    end);

    -- 关注喂食后的事件
    EventMgr.register("UIMonsterCaptain", event.FEED_MONSTER_CAPTAIN, function(args)
        self:redrawAttrib();
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIMonsterCaptain 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UIMonsterCaptain");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 注册点击事件
function UIMonsterCaptain:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIMonsterCaptain");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

end

-- 初始化窗口
function UIMonsterCaptain:initForm()
    local panel = findChildByName(self.node, "CT/panel");
    self.panel = panel;

    local panelWidth  = panel:getContentSize().width;
    local panelHeight = panel:getContentSize().height;

    local posY = panelHeight/2;

    local iconWidth  = 94;
    local iconHeight = 94;

    -- 图标与图标直接的间距
    local gap = 25;

    -- 左间距
    local leftWap = 20;

    for i = 1, #equipList do
        local child = cc.CSLoader:createNode("layout/bine/SkillIcon.csb");
        child:setName("item" .. i);
        local posX = iconWidth / 2 + (i - 1)*(iconWidth + gap) + leftWap;
        child:setPosition(posX, posY);
        panel:addChild(child);

        -- 注册框点击事件
        local frameImage = findChildByName(child, "frame");
        frameImage:setTouchEnabled(true);
        local function onFrameClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");

                -- 打开装备介绍界面
                local uiForm = UIMonsterCaptainEquip.create(equipList[i], self.summon:getPos(), i);
                UIMgr.getCurrentScene():addForm(uiForm);
            end
        end
        frameImage:addTouchEventListener(onFrameClick);
    end

    -- 初始化光效节点
    local effectNode  = findChildByName(self.node, "CT/left_part/effect_node");
    local effectNode2 = findChildByName(self.node, "CT/left_part/effect_node2");
    effectNode:setScale(EFFECT_SCALE);
    effectNode2:setScale(EFFECT_SCALE);
end

-- 重绘
function UIMonsterCaptain:redraw()
    -- 显示标题
    local name = SummonM.query(self.summon.classId, "name");
    local titleLabel = findChildByName(self.node, "CT/bg1/bg/title_label");
    titleLabel:setString(name);
    TextStyleM.setArtWordTitleStyle(titleLabel);

	-- 显示名字和介绍
    local nameLabel = findChildByName(self.node, "CT/monster_name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(name);

    local descLabel = findChildByName(self.node, "CT/monster_desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    local desc = SummonM.query(self.summon.classId, "desc");
    descLabel:setString(desc["desc1"]);

    local descLabel2 = findChildByName(self.node, "CT/monster_desc2");
    TextStyleM.setTextStyle(descLabel2, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN, false, -1);
    descLabel2:setString(desc["desc2"]);

    self:fixPos(descLabel, descLabel2, nameLabel);

    -- 显示海怪船长模型
    self:createSummonDisplay();

    -- 显示海怪船长属性
    self:redrawAttrib();

    -- 显示海怪船长装备
    self:redrawPanel();

end

-- 显示海怪船长属性
function UIMonsterCaptain:redrawAttrib()
    local valueLabel, nameLabel;
    local rightPart = findChildByName(self.node, "CT/bg1/right_part");

    local attack = self.summon:getAttack();

    -- 攻击
    nameLabel = findChildByName(rightPart, "attack_node/name");
    valueLabel= findChildByName(rightPart, "attack_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("attack"));
    valueLabel:setString(tostring(attack));

    -- 生命
    local nameLabel= findChildByName(rightPart, "hp_node/name");
    local valueLabel= findChildByName(rightPart, "hp_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("hp"));
    local curHp = math.max(0, self.summon:getHp());
    valueLabel:setString(curHp);

    -- 魔力
    local nameLabel= findChildByName(rightPart, "dodge_node/name");
    local valueLabel= findChildByName(rightPart, "dodge_node/value");
    local iconImg = findChildByName(rightPart, "dodge_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("magic"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("magic"));
    valueLabel:setString("--");

    -- 魔法
    -- 魔法
    local nameLabel= findChildByName(rightPart, "accuracy_node/name");
    local valueLabel= findChildByName(rightPart, "accuracy_node/value");
    local iconImg = findChildByName(rightPart, "accuracy_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("mp"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("mp"));
    valueLabel:setString("--");
end

-- 是否已经装备了
function UIMonsterCaptain:isEquiped(classId)
    -- 列表中只有三个，直接遍历
    local equipments = self.summon.equipments or {};
    for _, id in pairs(equipments) do
        if id == classId then
            return true;
        end
    end

    return false;
end

-- 显示海怪船长技能
function UIMonsterCaptain:redrawPanel()
    self.iconImgList = {};
    for i = 1, #equipList do
        local child    = findChildByName(self.panel, "item" .. i);
        local iconImg  = findChildByName(child, "icon");
        local starNode = findChildByName(child, "star_node");
        local frame    = findChildByName(child, "frame");

        table.insert(self.iconImgList, iconImg);

        local itemId = equipList[i];

        if itemId ~= 0 then
            -- 绘制图标
            iconImg:loadTexture(getItemIconPath(ItemM.query(itemId, "icon")));

            setGrayMode(iconImg, false);

            -- 如果该装备已装上
            if self:isEquiped(itemId) then
                setGrayMode(iconImg, false);
                frame:setOpacity(255);
            else
                -- 灰化处理
                setGrayMode(iconImg, true);

                -- 框需要半透明
                frame:setOpacity(100);

                if ItemM.getAmount(ME.user, itemId) > 0 then
                    -- 可穿戴，播放气泡动画
                    playBubbleAnima(iconImg, false);
                end
            end
        else
            -- 喂食按钮
            iconImg:setVisible(false);
            playLearnSkillHintEffect(frame, 54, 57);
        end
    end
end

-- 创建海怪船长模型
function UIMonsterCaptain:createSummonDisplay()
    local classId = self.summon.classId;
    local monsterNode = findChildByName(self.node, "CT/left_part/model_node");
    if monsterNode.summonDisplay then
        -- 先移除旧模型
        monsterNode:removeChild(monsterNode.summonDisplay);
    end

    -- 创建模型
    local summonDisplay = SummonDisplay.create(classId);

    -- 设置缩放比例
    local scale = SummonM.query(classId, "model_scale");
    summonDisplay:setScale(scale);

    -- 设置偏移量
    local offsetX = 0;
    local offsetY = 10;
    summonDisplay:setPosition(tonumber(offsetX), tonumber(offsetY));

    monsterNode:addChild(summonDisplay);

    monsterNode:setScale(1.5);
end

-- 选择装备事件处理
function UIMonsterCaptain:whenInputEquip(args)
    local equipId = args.classId;
    local index = args.index;
    if not equipId or not index then
        return;
    end

    local needPlayEffect = false;
    if index == #equipList then
        local pos = self.summon:getPos();
        local grid = DungeonM.getGridByPos(pos);
        DungeonActionM.go("submit_monster_captain", pos, equipId);

        -- 喂食完之后可能这个界面就要关掉了
        if grid.state == GRID_STATE_DISABLE then
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIMonsterCaptain");
            return;
        end

        -- 更新格子上的血量和攻击
        local grid = UIDungeonMgr.getCurLevel():getAllGrids()[self.summon:getPos()];
        grid:updateSummonHPAndAttack();
    end
end

-- 装备成功
function UIMonsterCaptain:onEquip(index)
    -- 重绘装备格
    self:redraw();

    -- 播放金属闪过的光效
    playEffect(self.iconImgList[index], 1186, 45, 45);

    -- 更新格子上的血量和攻击
    local grid = UIDungeonMgr.getCurLevel():getAllGrids()[self.summon:getPos()];
    grid:updateSummonHPAndAttack();
end